package org.app.original;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


import org.app.Ports;
import org.app.MyUtils;
import org.app.data.MyBean;
import org.app.entities.MyCoordinate;
import org.app.entities.Users;

public class MyJSON {
	//分隔符
	String[] ARRAY=new String[]{"[","]"};
	String[] MAP=new String[]{"{","}"};
	String PARALLEL=",";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		char c = 'z';
		System.out.println(new StringBuffer(c).append('j'));
		Class type = MyBean.class;
		System.out.println(type.getClassLoader() == null);

		MyJSON demo = new MyJSON();
		MyCoordinate my = new MyCoordinate();
		Map map = demo.toMap(my);
		MyUtils.show(map);

		System.out.println(my.getClass().getClassLoader() == null);
		String temp = demo.toJSON(my).toString();

		Users user = new Users();

		List list = new ArrayList();
		list.add(new Users());
		list.add(new Users());
		user.setList(list);
		temp = demo.toJSON(user).toString();
		System.out.println(temp);
		System.out.println("^_^");

		// temp=String.format("%s,%s",new String[]{"html","table"} );
		list = new ArrayList();
		list.add("table");
		list.add("tr");
		temp = String.format("%s,%s", list.toArray());
		System.out.println(temp);
	}

	/**
	 * 加密json即转换为bean
	 * 
	 * @param type
	 * @param json
	 * @return
	 */
	public <T> T Encrypt(Class<T> type, String json) {
		return null;
	}

	/**
	 * 解密 bean转换为json
	 * 
	 * @param t
	 * @return
	 */
	public <T> String Decrypt(T t) {
		return toJSON(t).toString();// 未格式化处理
	}

	private <T> Map toMap(final T t) {
		final Map map = new HashMap();
		// System.out.println(t);
		MyBean.visit(t, new Ports() {

			@Override
			public Object execute(Object obj) {
				// TODO Auto-generated method stub
				// if(obj instanceof PropertyDescriptor){
				PropertyDescriptor pd = (PropertyDescriptor) obj;
				Class type = pd.getPropertyType();
				String name = pd.getName();
				if (name.equals("class"))
					return null;

				// System.out.println(pd.getName());
				try {
					map.put(pd.getName(), pd.getReadMethod().invoke(t));
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// }
				return null;
			}

		});
		return map;
	}

	public <T> StringBuffer toJSON(T t) {
		StringBuffer sb = new StringBuffer();
		if (t == null)
			return sb;
		if (t instanceof Number) {
			sb.append(t);
		} else if (t instanceof String) {
			sb.append(String.format("\"%s\"", t.toString()));
		} else if (t.getClass().getClassLoader() != null) {// 用户自定义类型
			Map map = this.toMap(t);
			sb.append(toJSON(map));
		} else if (t instanceof Map) {
			// sb.append(t);
			//sb.append("{");
			Map map = (Map) t;
			Set<Entry> set = map.entrySet();
			String[] format=new String[map.size()];
			int id=0;
			for (Entry<String,Object> entry : set) {
				StringBuffer value = toJSON(entry.getValue());
				if (value.length() == 0) {
				//	format[id++]="";
					continue;
				}
				/// sb.append(string).append(entry.getKey()).append(string).append(mapper).append(value).append(parallel);
//				sb.append(String.format("\"%s\":%s,", entry.getKey(),
//						toJSON(entry.getValue())));
				format [id++]=String.format("\"%s\":%s", entry.getKey(),toJSON(entry.getValue()));

			}
			// sb.setCharAt(sb.length()-1, "}");
			// String type=t.getClass().toString().split(" ");

//			sb.append(String
//					.format("\"class\":\"%s\"}", t.getClass().getName()));
			
			sb.append(String.format(getFormat(id,MAP), format));

		}
		if (t instanceof List) {
			// sb.append(t);

			List list = (List) t;
			int size = list.size();
			if (size <= 0)
				return sb;

			// String array=this.getArrayFormat(size);
			String[] format = new String[size];
			for (int i = 0; i < size; i++) {
				// sb.append(String.format("%s,", toJSON(obj)));
				format[i] = toJSON(list.get(i)).toString();
			}

			// sb.setCharAt(sb.length()-1, parallelRight);
			sb.append(String.format(this.getFormat(size,ARRAY), format));
		}
		if (t.getClass().isArray()) {
			int size = Array.getLength(t);
			if (size <= 0)
				return sb;
			String[] format = new String[size];
			for (int i = 0; i < size; i++) {
				// sb.append(String.format("%s,", toJSON(obj)));
				format[i] = toJSON(Array.get(t, i)).toString();
			}

			// sb.setCharAt(sb.length()-1, parallelRight);
			sb.append(String.format(this.getFormat(size,ARRAY), format));

		}
		return sb;
	}

//	public String getArrayFormat(int size) {
//		StringBuffer sb = new StringBuffer();
//		if (size > 0) {
//			sb.append(ARRAY[0]+"%s");
//		} else {
//			sb.append(ARRAY[0]+ARRAY[1]);
//			return sb.toString();
//		}
//		for (int i = 1; i < size; i++) {
//			sb.append(PARALLEL+"%s");
//		}
//		sb.append("ARRAY[1]");
//		return sb.toString();
//	}
	
	public String getFormat(int size,String []type){
		StringBuffer sb = new StringBuffer();
		if (size > 0) {
			sb.append(type[0]+"%s");
		} else {
			sb.append(type[0]+type[1]);
			return sb.toString();
		}
		for (int i = 1; i < size; i++) {
			sb.append(PARALLEL+"%s");
		}
		sb.append(type[1]);
		return sb.toString();
	}

}
